package com.baitiaojun.video.service.impl;

import com.baitiaojun.api.domain.video.VideoCollection;
import com.baitiaojun.api.domain.video.VideoOperation;
import com.baitiaojun.api.exception.ConditionException;
import com.baitiaojun.api.util.ConstantUtil;
import com.baitiaojun.api.util.SnowFlakeUtil;
import com.baitiaojun.api.vo.LikeCoinOperatedCollectedInfo;
import com.baitiaojun.video.config.properties.CollectionGroupProperties;
import com.baitiaojun.video.mapper.VideoCollectionMapper;
import com.baitiaojun.video.mapper.VideoOperationMapper;
import com.baitiaojun.video.service.VideoCollectionService;
import com.baitiaojun.video.service.VideoService;
import com.baitiaojun.video.support.RedisSupport;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @类名 VideoCollectionServiceImpl
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2022/12/23 12:31
 * @版本 1.0
 */
@Service
public class VideoCollectionServiceImpl implements VideoCollectionService {

    @Resource
    private CollectionGroupProperties collectionGroupProperties;

    @Resource
    private VideoCollectionMapper videoCollectionMapper;

    @Resource
    private RedisSupport redisSupport;

    @Autowired
    private VideoService videoService;

    @Resource
    private VideoOperationMapper videoOperationMapper;

    //添加和更新视频收藏
    @Override
    @Transactional
    public void addVideoCollection(Long videoId, Long userId, Long groupId) throws Exception {
        //查看是否存在这条视频内容
        Integer isExists = videoService.isExistsVideo(videoId);
        if (ObjectUtils.isEmpty(isExists)) {
            throw new ConditionException("不存在此视频");
        }
        //用户不能收藏自己的视频
        Long uId = videoService.getUserIdByVideoId(videoId);
        if (userId.equals(uId)) {
            throw new ConditionException("收藏失败，up主不能给自己的视频收藏~");
        }
        //如果不存在自定义收藏夹就添加到默认收藏夹
        if (ObjectUtils.isEmpty(groupId)) {
            groupId = collectionGroupProperties.getId()[0];
        }
        //无论是否收藏过这个视频都先进行取消收藏操作，防止黑客攻击
        videoCollectionMapper.deleteCollection(videoId, userId);
        //双删机制
        redisSupport.delete(ConstantUtil.Field.VIDEO_COLLECTION.getKey() + userId);
        //添加视频收藏
        int res2 = videoCollectionMapper.insertSelective(VideoCollection.builder()
                .id(SnowFlakeUtil.getNextId())
                .videoid(videoId)
                .userid(userId)
                .groupid(groupId)
                .createtime(new Date())
                .build());
        if (res2 == 0) {
            throw new ConditionException("添加视频收藏失败");
        }
        //添加视频收藏操作记录
        VideoOperation videoOperation = new VideoOperation();
        videoOperation.setId(SnowFlakeUtil.getNextId());
        videoOperation.setUserid(userId);
        videoOperation.setVideoid(videoId);
        videoOperation.setCreatetime(new Date());
        videoOperation.setOperationtype("1");
        int resVideoOperation = videoOperationMapper.insertSelective(videoOperation);
        if (resVideoOperation == 0) {
            throw new ConditionException("添加视频操作记录失败");
        }
        redisSupport.delete(ConstantUtil.Field.VIDEO_COLLECTION.getKey() + userId);
    }

    @Transactional
    @Override
    public void cancelVideoCollection(Long videoId, Long userId) throws Exception {
        int res = videoCollectionMapper.deleteCollection(videoId, userId);
        if (res == 0) {
            throw new ConditionException("取消视频收藏失败");
        }
        redisSupport.delete(ConstantUtil.Field.VIDEO_COLLECTION.getKey() + userId);
        //删除视频收藏操作记录
        VideoOperation videoOperation = new VideoOperation();
        videoOperation.setUserid(userId);
        videoOperation.setVideoid(videoId);
        videoOperation.setOperationtype("1");
        int resVideoOperation = videoOperationMapper.deleteVideoOperation(videoOperation);
        if (resVideoOperation == 0) {
            throw new ConditionException("删除视频收藏记录失败");
        }
        redisSupport.delete(ConstantUtil.Field.VIDEO_COLLECTION.getKey() + userId);
    }

    @Override
    public LikeCoinOperatedCollectedInfo getVideoCollection(Long videoId, Long userId) {
        int count = videoCollectionMapper.selectVideoCollectionCount(videoId);
        Integer isCollected = videoCollectionMapper.isCollected(videoId, userId);
        return LikeCoinOperatedCollectedInfo.builder().count(count).flag("collected", ObjectUtils.isNotEmpty(isCollected)).build();
    }

    @Override
    public List<VideoCollection> selectVideoCollectionByUserId(Long userId) {
        return videoCollectionMapper.selectVideoCollectionByUserId(userId);
    }

    @Override
    public void batchCancelVideoCollections(Long groupId) throws ConditionException {
        int res = videoCollectionMapper.deleteVideoCollectionByGroupId(groupId);
        if (res == 0) {
            throw new ConditionException("批量删除失败");
        }
    }

    @Override
    public Integer isExistsVideoCollections(Long groupId) {
        return videoCollectionMapper.isExistsVideoCollections(groupId);
    }
}